package alp.starcode.nudtportal.framework.login.user;

import alp.starcode.common.dict.template.DictTemplate;
import alp.starcode.nudtportal.framework.constant.CampusStatusEnum;
import alp.starcode.nudtportal.framework.constant.ProjectConst;
import alp.starcode.nudtportal.framework.mybatis.dao.impl.*;
import alp.starcode.nudtportal.framework.mybatis.entity.UserAccount;
import alp.starcode.nudtportal.framework.mybatis.entity.UserConfig;
import alp.starcode.nudtportal.framework.mybatis.entity.UserRole;
import alp.starcode.nudtportal.framework.mybatis.entity.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@Slf4j
@Component("buildSessionUser")
public class BuildSessionUserRestImpl implements BuildSessionUser {
    @Autowired
    UserAccountDaoImpl userAccountDao;
    @Autowired
    UserServiceDaoImpl userServiceDao;
    @Autowired
    UserRoleDaoImpl userRoleDao;
    @Autowired
    LogUserLoginDaoImpl logUserLoginDao;
    @Autowired
    UserConfigDaoImpl userConfigDao;
    @Autowired
    DictTemplate dictTemplate;
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ElasticsearchRestTemplate restTemplate;


    @Override
    public void build(User sessionUser){
        UserAccount userAccount = userAccountDao.getById(sessionUser.getUserId());
        BeanUtils.copyProperties(userAccount, sessionUser);
        try {
            LambdaQueryWrapper<UserService> userServiceWrapper = new LambdaQueryWrapper<>();
            userServiceWrapper.eq(UserService::getUserId, sessionUser.getUserId())
                    .eq(UserService::getServiceCode, dictTemplate.getDictValueByDictLabel(ProjectConst.EASY_TONG_CAMPUS));
            UserService one = userServiceDao.getOne(userServiceWrapper);
            if (one != null) {
                sessionUser.setCampusEndTime(one.getServiceEndTime());
            }
        } catch (Exception e) {
            log.info("获取用户：{}，一卡通结束时间失败！失败原因：{}", sessionUser.getUserId(), e);
        }
        LambdaQueryWrapper<UserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(UserRole::getRoleId);
        lambdaQueryWrapper.eq(UserRole::getUserId, userAccount.getUserId());
        lambdaQueryWrapper.eq(UserRole::getIsDisabled, false);
        List<UserRole> userRoles = userRoleDao.list(lambdaQueryWrapper);
        Set<String> roleUuids = new HashSet<>();
        for (UserRole userRole : userRoles) {
            roleUuids.add(userRole.getRoleId());
        }
        //添加账号状态
        sessionUser.setCampusStatus(CampusStatusEnum.getNameByStatus(userAccount.getCampusStatus()));
        sessionUser.setRoleUuids(roleUuids);
        LambdaQueryWrapper<UserConfig> userConfigWrapper = new LambdaQueryWrapper<>();
        userConfigWrapper.select(UserConfig::getConfigValue);
        userConfigWrapper.eq(UserConfig::getUserId, userAccount.getUserId());
        userConfigWrapper.eq(UserConfig::getConfigItem, ProjectConst.USER_CONFIG_HOME_MODULE_SIZE);
        UserConfig userConfig = userConfigDao.getOne(userConfigWrapper);
        try {
            sessionUser.setHomeModuleLimitSize(userConfig == null ?
                    dictTemplate.getDictValueByDictLabel(ProjectConst.DEFAULT_MODULE_DISPLAY) : userConfig.getConfigValue());
            if (userConfig == null) {
                userConfig = new UserConfig();
                userConfig.setUserConfigId(UUID.randomUUID().toString());
                userConfig.setUserId(userAccount.getUserId());
                userConfig.setConfigItem(ProjectConst.USER_CONFIG_HOME_MODULE_SIZE);
                userConfig.setConfigValue(dictTemplate.getDictValueByDictLabel(ProjectConst.DEFAULT_MODULE_DISPLAY));
                userConfig.setDataSource(ProjectConst.USER_CONFIG_DATA_SOURCE_SYSTEM);
                userConfig.setCreateTime(System.currentTimeMillis());
                userConfig.setUpdateTime(System.currentTimeMillis());
                userConfigDao.save(userConfig);
            }
        } catch (Exception e) {
            sessionUser.setHomeModuleLimitSize("4x4");
            log.info("获取用户：{}，首页展示模块数量失败！失败原因：{}", sessionUser.getUserId(), e);
        }
    }

}
